<template>
  <a-modal
    :title="title"
    :width="1200"
    :visible="visible"
    :maskClosable="false"
    switchFullscreen
    @cancel="handleCancel"
    :confirmLoading="confirmLoading"
    v-drag
  >
    <div>
      <a-row style="margin-bottom: 20px">
        <a-col :span="24">
          <a-button v-if="dataForm.id" type="primary" @click="handleExportXls($t('出库单详情'))">{{
            $t('导出')
          }}</a-button>
          <a-button v-if="state == 1 || state == 2" type="primary" @click="printReport" style="margin-left: 8px">{{
            $t('打印')
          }}</a-button>
        </a-col>
      </a-row>
      <div>
        <div style="width: 40%;margin-bottom:20px;">
          {{ $t('出库仓库:') }}
          <j-dict-select-tag
            :placeholder="$t('请选择')"
            v-model="dataForm.store"
            style="width: 300px"
            dictCode="bis_goods_store,name,id"
            @change="changStore(true)"
            v-if="state != 1 && state != 2"
          />
          <span v-if="state == 1 || state == 2">{{dataForm.store_dictText}}</span>
        </div>
        <div v-if="state != 1 && state != 2" style="margin: 10px; font-size: 14px; font-weight: bold">
          {{ $t('商品列表') }}:
        </div>
        <a-table
          :columns="columns"
          :dataSource="dataSource"
          size="middle"
          bordered
          class="j-table-force-nowrap"
          :pagination="false"
          style="padding-left: 11px"
        >
          <template slot="action" slot-scope="text, record">
            <a-icon type="close" @click="deleteGoods(text, record)" />
          </template>
          <template slot="selectGoods" slot-scope="text, record">
            <span v-if="state == 1 || state == 2">{{ record.goodsId_dictText }}</span>
            <a-select
              v-else
              v-model="record.goodsId"
              show-search
              :placeholder="$t('请选择商品')"
              :filter-option="false"
              :not-found-content="null"
              @search="handleGoodsSearch"
              style="width:100%"
            >
              <a-select-option key="99999999" :label="$t('标题')" value="99999999" disabled>
                <span style="display: inline-block; width: 240px; color: #000; font-weight: bold">{{
                  $t('名称')
                }}</span>
                <span style="display: inline-block; width: 60px; color: #000; font-weight: bold">{{ $t('库存') }}</span>
              </a-select-option>
              <a-select-option
                v-for="item in addGoodsList"
                :key="item.id"
                :label="item.goodsId_dictText"
                :value="item.goodsId"
                @click="handleSelectGoods(record, item)"
              >
                <span style="display: inline-block; width: 240px">{{ item.goodsId_dictText }}</span>
                <span style="display: inline-block; width: 60px">{{ item.stock }}</span>
              </a-select-option>
            </a-select>
          </template>
          <template slot="number" slot-scope="text, record">
            <a-input v-model="record.number" @change="handleAmount(record)" ref="number"></a-input>
          </template>
          <template slot="totalAmount" slot-scope="text, record">
            <a-input v-model="record.totalAmount" @change="handleAmount(record)" ref="totalAmount"></a-input>
          </template>
          <template slot="comment" slot-scope="text, record">
            <a-input v-model="record.comment"></a-input>
          </template>
        </a-table>
        <div style="margin-top: 20px; font-weight: bolder">
          {{ $t('总数量') }}:{{ totalNum }} &nbsp;
          {{ $t('总金额') }}:{{ totalAmo }} &nbsp; 
          {{ $t('出库类型') }}:
          <a-select v-model="dataForm.outType" style="width: 180px" v-if="state != 1 && state != 2">
            <a-select-option v-for="(item, index) in outtypeList" :value="item.id" :key="index">{{
              item.name
            }}</a-select-option>
          </a-select>
          <span v-if="state == 1 || state == 2">{{dataForm.outType_dictText}}</span>
          <a v-if="state == 0" @click="addOutType" style="margin-left: 8px">{{ $t('新增') }}</a>
          {{ $t('备注') }}:&nbsp;
          <a-input
            v-if="state != 1 && state != 2"
            style="width: 300px"
            v-model="dataForm.comment"
            :placeholder="$t('请输入备注')"
          />
          <span v-if="state == 1 || state == 2">{{ dataForm.comment }}</span>
        </div>
      </div>
    </div>
    <template slot="footer">
      <a-button type="primary" :disabled="confirmLoading" v-if="state == 0" @click="handleOk(0)">{{
        $t('保存')
      }}</a-button>
      <a-button type="primary" :disabled="confirmLoading" v-if="state != 1" @click="handleOk(1)">{{
        $t('保存并审核')
      }}</a-button>
      <a-button @click="handleCancel">{{ $t('关闭') }}</a-button>
    </template>
    <edit-out-type-modal ref="editForm" @ok="modalFormOk"></edit-out-type-modal>
    <goods-print-modal ref="printModal"></goods-print-modal>
  </a-modal>
</template>

<script>
import { getAction, httpAction, downFile } from '@/api/manage'
import EditOutTypeModal from './EditOutTypeModal'
import GoodsPrintModal from './GoodsPrintModal'
let _self
export default {
  name: 'OtherOutOfStoreModal',
  components: {
    EditOutTypeModal,GoodsPrintModal
  },
  data() {
    return {
      title: '',
      width: 800,
      visible: false,
      confirmLoading: false,
      disableSubmit: false,
      dataForm: {
        outType: '',
      },
      addGoodsList: [],
      dataSource: [],
      columns: [],
      columns1: [
        {
          title: '+',
          dataIndex: 'action',
          align: 'center',
          width: 30,
          customHeaderCell: function (column) {
            return {
              style: {
                textAlign: 'center',
                color: '#1890ff',
                fontSize: '25px',
                height: '32px',
                lineHeight: '32px',
                fontWeight: 'bold',
                cursor: 'pointer',
              },
              on: {
                click: () => {
                  _self.addGoods()
                },
              },
            }
          },
          customCell: function (column) {
            return {
              style: {
                textAlign: 'center',
                color: '#1890ff',
                fontSize: '16px',
                height: '32px',
                lineHeight: '32px',
                fontWeight: 'bold',
                cursor: 'pointer',
              },
            }
          },
          scopedSlots: { customRender: 'action' },
        },
        {
          title: this.$t('序号'),
          dataIndex: '',
          key: 'rowIndex',
          align: 'center',
          width: 100,
          customRender: function (t, r, index) {
            return parseInt(index) + 1
          },
        },
        {
          title: this.$t('商品编码'),
          dataIndex: 'goodsCode',
          align: 'center',
          width: 90,
        },
        {
          title: this.$t('商品名称'),
          dataIndex: 'goodsId',
          align: 'center',
          width: 360,
          scopedSlots: { customRender: 'selectGoods' },
        },
        {
          title: this.$t('出库数量'),
          key: 'number',
          dataIndex: 'number',
          align: 'center',
          customCell: function (record, rowIndex) {
            return {
              style: {
                textAlign: 'right',
              },
            }
          },
          scopedSlots: { customRender: 'number' },
        },
        {
          title: this.$t('单位'),
          key: 'unit_dictText',
          dataIndex: 'unit_dictText',
          align: 'center',
        },
        {
          title: this.$t('规格'),
          key: 'standard',
          dataIndex: 'standard',
          align: 'center',
        },
        {
          title: this.$t('成本'),
          key: 'unitPrice',
          dataIndex: 'unitPrice',
          align: 'center',
          customCell: function (record, rowIndex) {
            return {
              style: {
                textAlign: 'right',
              },
            }
          },
        },
        {
          title: this.$t('总成本'),
          key: 'totalAmount',
          dataIndex: 'totalAmount',
          align: 'center',
          customCell: function (record, rowIndex) {
            return {
              style: {
                textAlign: 'right',
              },
            }
          },
        },
        {
          title: this.$t('备注'),
          key: 'comment',
          dataIndex: 'comment',
          align: 'center',
          scopedSlots: { customRender: 'comment' },
        },
      ],
      columns2: [
        {
          title: this.$t('序号'),
          dataIndex: '',
          key: 'rowIndex',
          align: 'center',
          width: 100,
          customRender: function (t, r, index) {
            return parseInt(index) + 1
          },
        },
        {
          title: this.$t('商品编码'),
          dataIndex: 'goodsCode',
          align: 'center',
          width: 90,
        },
        {
          title: this.$t('商品名称'),
          dataIndex: 'goodsId',
          align: 'center',
          width: 360,
          scopedSlots: { customRender: 'selectGoods' },
        },
        {
          title: this.$t('出库数量'),
          key: 'number',
          dataIndex: 'number',
          align: 'center',
          customCell: function (record, rowIndex) {
            return {
              style: {
                textAlign: 'right',
              },
            }
          },
        },
        {
          title: this.$t('单位'),
          key: 'unit_dictText',
          dataIndex: 'unit_dictText',
          align: 'center',
        },
        {
          title: this.$t('规格'),
          key: 'standard',
          dataIndex: 'standard',
          align: 'center',
        },
        {
          title: this.$t('成本'),
          key: 'unitPrice',
          dataIndex: 'unitPrice',
          align: 'center',
          customCell: function (record, rowIndex) {
            return {
              style: {
                textAlign: 'right',
              },
            }
          },
        },
        {
          title: this.$t('总成本'),
          key: 'totalAmount',
          dataIndex: 'totalAmount',
          align: 'center',
          customCell: function (record, rowIndex) {
            return {
              style: {
                textAlign: 'right',
              },
            }
          },
        },
        {
          title: this.$t('业务前库存'),
          key: 'beforeNum',
          dataIndex: 'beforeNum',
          customHeaderCell: function (column) {
            return {
              style: {
                textAlign: 'center',
              },
            }
          },
          customCell: function (record, rowIndex) {
            return {
              style: {
                textAlign: 'right',
              },
            }
          },
        },
        {
          title: this.$t('业务后库存'),
          key: 'afterNum',
          dataIndex: 'afterNum',
          customHeaderCell: function (column) {
            return {
              style: {
                textAlign: 'center',
              },
            }
          },
          customCell: function (record, rowIndex) {
            return {
              style: {
                textAlign: 'right',
              },
            }
          },
        },
        {
          title: this.$t('备注'),
          key: 'comment',
          dataIndex: 'comment',
          align: 'center',
        },
      ],
      url: {
        add: '/goods/bisGoodsOutstock/add',
        edit: '/goods/bisGoodsOutstock/edit',
        exportXlsUrl: '/goods/bisGoodsOutstock/detailExportXls',
      },
      totalNum: 0,
      totalAmo: 0,
      state: 0,
      outtypeList: [],
    }
  },
  created() {
    _self = this
  },
  methods: {
    add() {
      this.columns = this.columns1
      this.visible = true
      this.dataSource = []
      this.edit()
    },
    edit(record, state) {
      this.visible = true
      this.confirmLoading = false
      this.totalAmo = 0
      this.totalNum = 0
      if (state == undefined) {
        this.state = 0
        this.columns = this.columns1
      } else {
        this.state = state
        this.columns = this.columns2
      }
      this.dataForm = Object.assign({}, record)
      if (record) {
        this.getTypeList()
        getAction('/goods/bisGoodsOutstock/queryBisGoodsOutstockDetailsByMainId', { id: record.id }).then((res) => {
          if (res.success) {
            this.dataSource = res.result
            let arr = []
            this.dataSource.forEach((col) => {
              let dtl = {
                goodsId: col.goodsId,
                goodsId_dictText: col.goodsId_dictText,
              }
              arr.push(dtl)
              this.totalNum += col.number
              this.totalAmo += col.totalAmount
            })
            this.addGoodsList = arr
            this.totalAmo = this.totalAmo.toFixed(2)
          }
        })
      } else {
        this.getTypeList(0)
      }
    },
    getTypeList(num) {
      getAction('/goods/bisGoodsOutstockType/list', { pageSize: 999 }).then((res) => {
        if (res.success) {
          this.outtypeList = res.result.records
          // if(num == 0){
          //   this.dataForm.outType = this.outtypeList[0].id
          // }
          if (num == 1) {
            this.dataForm.outType = this.outtypeList[this.outtypeList.length - 1].id
          }
        }
      })
    },
    addGoods() {
      if (this.dataForm.store == '' || this.dataForm.store == undefined) {
        this.$message.warning(this.$t('请选择要出库的仓库'))
        return
      } else {
        let obj = {
          goodsCode: '',
          goodsId_dictText: '',
          number: '',
          unit_dictText: '',
          standard: '',
          unitPrice:'',
          totalAmount: '',
          comment: '',
        }
        this.dataSource.push(obj)
      }
    },
    handleSelectGoods(record, good) {
      record.goodsCode = good.goodsCode
      record.goodsId_dictText = good.goodsId_dictText
      record.unitPrice = good.cost
      record.stock = good.stock
      record.unit_dictText = good.unit_dictText
      record.standard = good.standard
    },
    changStore(state) {
      let that = this
      if (state) {
        if (that.dataSource.length > 0) {
          that.$confirm({
            title: that.$t('提示'),
            content: that.$t('切换仓库将清空商品列表，确定要切换吗？'),
            okText: that.$t("确定"),
            cancelText: that.$t("取消"),
            onOk() {
              that.dataSource = []
              return
            },
            onCancel() {},
          })
        }
      }
      that.getGoodsList()
    },
    handleGoodsSearch(value) {
      this.getGoodsList(value)
    },
    getGoodsList(value) {
      let that = this
      let querydata = {}
      that.addGoodsList = []
      querydata.pageNo = 1
      querydata.pageSize = 10
      querydata.goodsInfo = value
      querydata.storeId = that.dataForm.store
      getAction('/goods/bisGoodsStock/list', querydata).then((res) => {
        if (res.success) {
          that.addGoodsList = res.result.records
        }
      })
    },
    handleAmount(record) {
      if (record.number > record.stock) {
        this.$message.warning(this.$t('出库数量应小于等于当前库存'))
        return
      }
      if (record.number != '' && record.unitPrice != '') {
        record.totalAmount=(parseFloat(record.number)*parseFloat(record.unitPrice)).toFixed(2)
      }else{
        record.totalAmount='0'
      }
      this.totalNum = 0
      this.totalAmo = 0
      this.dataSource.forEach((res) => {
        this.totalNum = (res.number!=''?parseFloat(res.number):0) + parseFloat(this.totalNum)
        this.totalAmo = (res.totalAmount!=''?parseFloat(res.totalAmount):0) + parseFloat(this.totalAmo)
      })
    },
    deleteGoods(a, b) {
      this.dataSource.forEach((col) => {
        if (col.goodsId == b.goodsId) {
          let index = this.dataSource.indexOf(col)
          this.dataSource.splice(index, 1)
        }
      })
    },
    handleAddConditions() {
      this.$refs.handleModal.edit()
    },
    handleOk(state) {
      let that = this
      let querydata = {}
      querydata = that.dataForm
      if (querydata.store == undefined) {
        that.$message.warning(that.$t('请先选择出库仓库'))
        that.confirmLoading = false
        return
      }
      if (that.dataSource.length == 0) {
        that.$message.warning(that.$t('商品不能为空'))
        return
      }
      let i = 0
      that.dataSource.forEach((col) => {
        if (col.goodsId_dictText == '') {
          that.$message.warning(that.$t('商品名称不能为空'))
          return
        }
        if (col.number == '') {
          that.$message.warning(that.$t('出库数量不能为空'))
          that.$refs.number.focus()
          return
        }
        i++
      })
      if (querydata.outType == undefined) {
        that.$message.warning(that.$t('请选择出库类型'))
        return
      }
      if (i == that.dataSource.length) {
        that.confirmLoading = true
        querydata.bisGoodsOutstockDetailsList = that.dataSource
        querydata.state = state
        let httpurl = ''
        let method = ''
        if (!that.dataForm.id) {
          httpurl += that.url.add
          method = 'post'
        } else {
          httpurl += that.url.edit
          method = 'put'
        }
        httpAction(httpurl, querydata, method).then((res) => {
          if (res.success) {
            that.close()
            that.$message.success(res.message)
          } else {
            that.confirmLoading = false
            that.$message.warning(res.message)
          }
        })
      }
    },
    addOutType() {
      this.$refs.editForm.edit(false)
      this.$refs.editForm.title = this.$t('新增出库类型')
    },
    modalFormOk() {
      this.getTypeList(1)
    },
    handleCancel() {
      this.close()
    },
    close() {
      this.$emit('ok')
      this.visible = false
    },
    handleExportXls(fileName) {
      if (!fileName || typeof fileName != 'string') {
        fileName = '导出文件'
      }
      let param = {}
      param.orderId = this.dataForm.id
      console.log('导出参数', param)
      downFile(this.url.exportXlsUrl, param).then((data) => {
        if (!data) {
          this.$message.warning(this.$t('文件下载失败'))
          return
        }
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
          window.navigator.msSaveBlob(new Blob([data], { type: 'application/vnd.ms-excel' }), fileName + '.xls')
        } else {
          let url = window.URL.createObjectURL(new Blob([data], { type: 'application/vnd.ms-excel' }))
          let link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', fileName + '.xls')
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link) //下载完成移除元素
          window.URL.revokeObjectURL(url) //释放掉blob对象
        }
      })
    },
    printReport(){
      this.$refs.printModal.show(this.dataForm,2)
    }
  },
}
</script>

<style scoped>
</style>